﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Text.RegularExpressions;

namespace EnergyConsumptionMonitorSystem.Models
{
    public class TextBoxRestriction : DependencyObject
    {
        public static readonly DependencyProperty ValidateRegexProperty = DependencyProperty.RegisterAttached("ValidateRegex", typeof(string), typeof(TextBoxRestriction), new UIPropertyMetadata(null, OnValidateRegexChanged));

        public static string GetValidateRegex(DependencyObject obj)
        {
            return (string)obj.GetValue(ValidateRegexProperty);
        }

        public static void SetValidateRegex(DependencyObject obj, string value)
        {
            obj.SetValue(ValidateRegexProperty, value);
        }

        private static void OnValidateRegexChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            if (obj is TextBox)
            {
                TextBox txtBox = obj as TextBox;
                if (!String.IsNullOrEmpty((string)e.NewValue))
                {
                    txtBox.PreviewTextInput += PreviewTextInput;
                    DataObject.AddPastingHandler(txtBox, Pasting);
                }
                else
                {
                    txtBox.PreviewTextInput -= PreviewTextInput;
                    DataObject.RemovePastingHandler(txtBox, Pasting);
                }
            }
        }

        private static void Pasting(object sender, DataObjectPastingEventArgs e)
        {
            TextBox txtBox = sender as TextBox;
            if (e.DataObject.GetDataPresent(typeof(String)))
            {
                String text = (String)e.DataObject.GetData(typeof(String));
                if (!Validate(txtBox,text))
                { 
                    e.CancelCommand(); 
                }
            }
            else 
            { 
                e.CancelCommand(); 
            }

        }

        private static void PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            TextBox txtBox = sender as TextBox;
            if (!Validate(txtBox,txtBox.Text + e.Text))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }

        private static bool Validate(TextBox txtBox,string text)
        {
            Regex regex = new Regex(GetValidateRegex(txtBox));
            return regex.IsMatch(text);
        }
    }
}
